package com.tmall.testgen.client.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import com.tmall.testgen.common.ConnectionCommond;
import com.tmall.testgen.common.bo.interact.back.syn.ConnectionSuccResult;
import com.tmall.testgen.common.socket.SocketInfoListener;
import com.tmall.testgen.common.socket.TransferHandler;
import com.tmall.testgen.common.socket.syn.SynCallBack;
import com.tmall.testgen.common.socket.syn.SynObject;

/**
 * 客户端 只维持一个socket和out
 * @author haojia
 * @date 2014-07-04
 */
public class SocketClient {
	private  Socket socket;
	
	private  OutputStream out;
	private boolean isStart=false;
	
	private static SocketClient instance=new SocketClient();
	private static Object getConnectionSuccResultSyn=new Object();
	
	private ConnectionSuccResult result;
	public static SocketClient getInstance(){
		return instance;
	}

	public   ConnectionSuccResult startConnectServer(String serverIp) throws Exception {
		
		for(int i=0;i<5;i++){
			tryConn(serverIp);
			if(socket!=null&&socket.isConnected()&&!socket.isClosed())
				break;
			Thread.sleep(1000);
		}
		if(socket==null){
			throw new Exception("socket连接失败");
		}
		//ConsoleFactory.putMessage("socket连接成功");
		isStart=true;
		out =  socket.getOutputStream();
		
		new SocketInfoListener(socket,null,new ClientReceiveObjectHandler()).startListener();
		
//		ConnectionSuccResult result= (ConnectionSuccResult) new SynCallBack(){
//			@Override
//			public Object handleReceive(SynObject synObj) {
//				if( synObj instanceof ConnectionSuccResult){
//					return synObj;
//				}
//				return null;
//			}
//			
//		}.sendObj(null,out);
		synchronized (getConnectionSuccResultSyn) {
	           getConnectionSuccResultSyn.wait();
	       }
		
		return result;
	}
	
	
	public void setConnectionSuccResult(ConnectionSuccResult result){
	   synchronized (getConnectionSuccResultSyn) {
	       getConnectionSuccResultSyn.notifyAll();
	   }
	   this.result=result;
	}
	public  void closeSocket() {
		isStart=false;
		try {
			out.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	public  void writeObect(Object obj){
		 try {
			TransferHandler.writeObject(out, obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private  void tryConn(String ip) throws Exception{
		try {
			socket = new Socket(ip, ConnectionCommond.PORT);
		}catch(Exception e){e.printStackTrace();
		//	e.printStackTrace();
		}
		
	}

	public boolean isStart() {
		return isStart;
	}

    public OutputStream getOut() {
        return out;
    }
	
	
}
